package com.summer.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.summer.mall.common.ResponseCode;
import com.summer.mall.common.ResponseService;
import com.summer.mall.entity.Shipping;
import com.summer.mall.expection.MallException;
import com.summer.mall.mapper.ShippingMapper;
import com.summer.mall.service.ShippingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by complone on 2018/7/23.
 */
@Service("shippingService")
public class ShippingServiceImpl implements ShippingService{

    @Autowired
    private ShippingMapper shippingMapper;

    @Override
    public ResponseService add(Integer userId, Shipping shipping) {
        shipping.setUserId(userId);
        int rowCount = shippingMapper.insert(shipping);
        if(rowCount > 0){
            Map result = Maps.newHashMap();
            result.put("shippingId",shipping.getId());
            return ResponseService.createBySuccess("新建地址成功",result);
        }
        return ResponseService.createByErrorMessage("新建地址失败");
    }

    @Override
    public ResponseService update(Integer userId, Shipping shipping) {
        shipping.setUserId(userId);
        int rowCount = shippingMapper.updateByPrimaryKey(shipping);
        if (rowCount>0){
            return ResponseService.createBySuccessMessage("更新地址成功");
        }
        return ResponseService.createByErrorMessage("更新地址失败");
    }

    @Override
    public ResponseService<String> del(Integer userId, Integer shippingId) {
        int resultCount = shippingMapper.deleteByPrimaryKey(userId);
        if (resultCount>0){
            return ResponseService.createBySuccessMessage("删除地址成功");
        }
        return ResponseService.createByErrorMessage("删除地址失败");
    }

    @Override
    public ResponseService<Shipping> select(Integer userId, Integer shippingId) {
        Shipping shipping = shippingMapper.selectByShippingIdUserId(userId,shippingId);
        if(shipping == null){
            return ResponseService.createByErrorMessage("无法查询到该地址");
        }
        return ResponseService.createBySuccess("更新地址成功",shipping);
    }

    @Override
    public ResponseService<PageInfo> list(Integer userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Shipping> shippingList = shippingMapper.selectByUserId(userId);
        PageInfo pageInfo = new PageInfo(shippingList);
        if (pageInfo == null){
            throw new MallException(ResponseCode.PAGEINFO_NOT_EXIST);
        }
        return ResponseService.createBySuccess(pageInfo);
    }
}
